<template>
  <div class="smart-reconciliation-workbench">
    <!-- 工作台头部 -->
    <WorkbenchHeader 
      :stats="workbenchStats"
      @import-data="handleImportData"
      @smart-match="handleSmartMatch"
      @batch-operate="handleBatchOperate"
      @algorithm-change="handleAlgorithmChange"
    />

    <!-- 三栏主工作区 -->
    <div class="workbench-main">
      <!-- 左侧：银行流水面板 -->
      <div class="panel-left" :style="{ width: leftPanelWidth + 'px' }">
        <TransactionPanel 
          ref="transactionPanelRef"
          :transactions="pendingTransactions"
          :loading="transactionLoading"
          @selection-change="onTransactionSelect"
          @row-click="onTransactionClick"
          @filter-change="onTransactionFilter"
          @import="handleTransactionImport"
          @refresh="handleTransactionRefresh"
        />
        
        <!-- 面板调整手柄 -->
        <div 
          class="panel-resize-handle"
          @mousedown="startResize('left')"
        ></div>
      </div>

      <!-- 中间：智能匹配中心 -->
      <div class="panel-center">
        <MatchingCenter 
          :selected-transactions="selectedTransactions"
          :selected-orders="selectedOrders"
          :match-results="matchResults"
          :matching-status="matchingStatus"
          @quick-match="handleQuickMatch"
          @confirm-match="handleConfirmMatch"
          @reject-match="handleRejectMatch"
          @show-details="showMatchDetails"
          @algorithm-change="handleAlgorithmChange"
          @show-instructions="showInstructions"
        />

        <!-- 智能匹配浮动助手 -->
        <SmartMatchAssistant 
          v-if="showSmartAssistant"
          :transactions-count="pendingTransactions.length"
          :orders-count="pendingOrders.length"
          :match-suggestions="matchSuggestions"
          @apply-suggestion="applySmartSuggestion"
          @smart-match="handleSmartMatch"
          @close="showSmartAssistant = false"
        />
      </div>

      <!-- 右侧：销售订单面板 -->
      <div class="panel-right" :style="{ width: rightPanelWidth + 'px' }">
        <OrderPanel 
          ref="orderPanelRef"
          :orders="pendingOrders"
          :loading="orderLoading"
          @selection-change="onOrderSelect"
          @row-click="onOrderClick"
          @filter-change="onOrderFilter"
          @sync="handleOrderSync"
          @refresh="handleOrderSync"
        />
        
        <!-- 面板调整手柄 -->
        <div 
          class="panel-resize-handle"
          @mousedown="startResize('right')"
        ></div>
      </div>
    </div>

    <!-- 底部状态栏 -->
    <WorkbenchStatusBar 
      :selected-counts="selectedCounts"
      :match-stats="matchStats"
      :processing="processing"
      @clear-selection="clearAllSelection"
    />

    <!-- 匹配详情抽屉 -->
    <MatchDetailsDrawer 
      v-model="detailsDrawerVisible"
      :match-data="currentMatch"
      @confirm="handleConfirmMatch"
      @reject="handleRejectMatch"
    />

    <!-- 数据导入向导 -->
    <DataImportWizard 
      v-model="importWizardVisible"
      :import-type="currentImportType"
      @import-success="handleImportSuccess"
    />

    <!-- 智能匹配进度 -->
    <SmartMatchProgress 
      v-model="matchProgressVisible"
      :progress="matchProgress"
      :current-algorithm="currentAlgorithm"
      @cancel="cancelSmartMatch"
    />

    <!-- 批量操作面板 -->
    <BatchOperationPanel 
      v-model="batchPanelVisible"
      :selected-transactions="selectedTransactions"
      :selected-orders="selectedOrders"
      @batch-match="handleBatchMatch"
      @batch-ignore="handleBatchIgnore"
    />
    
    <!-- 操作指南对话框 -->
    <el-dialog
      v-model="instructionsDialogVisible"
      title="对账操作指南"
      width="800px"
      class="instructions-dialog"
    >
      <div class="instructions-content">
        <el-tabs v-model="activeInstructionTab">
          <el-tab-pane label="基础操作" name="basic">
            <div class="instruction-section">
              <h3>1. 数据准备</h3>
              <p>确保已导入银行流水和销售订单数据</p>
              <ul>
                <li>点击"导入流水"按钮导入银行流水数据</li>
                <li>点击"同步订单"按钮同步销售订单数据</li>
              </ul>
              
              <h3>2. 选择匹配项</h3>
              <p>在左侧和右侧面板中选择需要匹配的银行流水和销售订单</p>
              <ul>
                <li>单击行选择单个项目</li>
                <li>按住Ctrl键可多选</li>
                <li>按住Shift键可选择连续项目</li>
              </ul>
              
              <h3>3. 执行匹配</h3>
              <p>在中间匹配区域执行匹配操作</p>
              <ul>
                <li>点击"快速匹配"按钮进行手动匹配</li>
                <li>点击"查看详情"查看匹配详情</li>
                <li>点击"清除选择"取消当前选择</li>
              </ul>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="智能匹配" name="smart">
            <div class="instruction-section">
              <h3>智能匹配算法</h3>
              <p>系统提供多种匹配算法以适应不同场景</p>
              
              <div class="algorithm-info">
                <h4><el-icon><DataAnalysis /></el-icon> 综合算法</h4>
                <p>综合考虑金额、名称、时间等多个因素进行匹配，适用于大多数场景</p>
                
                <h4><el-icon><Check /></el-icon> 精确匹配</h4>
                <p>只匹配金额完全相同且名称高度相似的记录，准确率最高但匹配数量较少</p>
                
                <h4><el-icon><Coin /></el-icon> 金额优先</h4>
                <p>优先按金额相似度进行匹配，适合处理金额有微小差异的情况</p>
                
                <h4><el-icon><Timer /></el-icon> 时间窗口</h4>
                <p>在指定时间范围内进行匹配，适合处理时间相近的交易记录</p>
              </div>
              
              <h3>智能建议</h3>
              <p>系统会根据数据特征提供智能匹配建议</p>
              <ul>
                <li>高置信度建议：置信度&gt;80%，可直接应用</li>
                <li>中置信度建议：置信度50-80%，建议人工确认</li>
                <li>低置信度建议：置信度&lt;50%，仅供参考</li>
              </ul>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="批量操作" name="batch">
            <div class="instruction-section">
              <h3>批量操作流程</h3>
              <p>当需要处理大量数据时，可使用批量操作功能</p>
              
              <ol>
                <li>选择多个银行流水或销售订单</li>
                <li>点击顶部"批量操作"按钮</li>
                <li>在批量操作面板中选择操作类型：
                  <ul>
                    <li>批量匹配：将选中的流水和订单进行批量匹配</li>
                    <li>批量忽略：将选中的项目标记为已处理但不匹配</li>
                  </ul>
                </li>
                <li>确认操作并执行</li>
              </ol>
              
              <h3>注意事项</h3>
              <ul>
                <li>批量操作不可逆，请谨慎执行</li>
                <li>建议在执行前先查看匹配预览</li>
                <li>可随时点击"清除选择"取消批量操作</li>
              </ul>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="instructionsDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="instructionsDialogVisible = false">我知道了</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DataAnalysis,
  Check,
  Coin,
  Timer
} from '@element-plus/icons-vue'
import { useReconciliationStore } from '@/stores/reconciliationStore'
import { useAppStore } from '@/stores/appStore'

// 组件导入
import WorkbenchHeader from './components/WorkbenchHeader.vue'
import TransactionPanel from '@/components/reconciliation/TransactionPanel.vue'
import OrderPanel from '@/components/reconciliation/OrderPanel.vue'
import MatchingCenter from './components/MatchingCenter.vue'
import SmartMatchAssistant from './components/SmartMatchAssistant.vue'
import WorkbenchStatusBar from './components/WorkbenchStatusBar.vue'
import MatchDetailsDrawer from '@/components/reconciliation/MatchDetailsDrawer.vue'
import DataImportWizard from './components/DataImportWizard.vue'
import SmartMatchProgress from './components/SmartMatchProgress.vue'
import BatchOperationPanel from './components/BatchOperationPanel.vue'

// Store
const reconciliationStore = useReconciliationStore()
const appStore = useAppStore()
const router = useRouter()

// 响应式数据
const transactionPanelRef = ref()
const orderPanelRef = ref()

const leftPanelWidth = ref(400)
const rightPanelWidth = ref(400)
const isResizing = ref(false)
const resizeDirection = ref<'left' | 'right'>('left')

const transactionLoading = ref(false)
const orderLoading = ref(false)
const processing = ref(false)

const selectedTransactions = ref<any[]>([])
const selectedOrders = ref<any[]>([])
const matchResults = ref<any[]>([])
const currentMatch = ref<any>(null)
const confidenceBreakdown = ref<any>(null)

const matchingStatus = ref<'idle' | 'matching' | 'success' | 'error'>('idle')
const matchProgress = ref(0)
const currentAlgorithm = ref('comprehensive')
const matchSuggestions = ref<any[]>([])

// UI 状态
const detailsDrawerVisible = ref(false)
const importWizardVisible = ref(false)
const matchProgressVisible = ref(false)
const batchPanelVisible = ref(false)
const showSmartAssistant = ref(false)

// 操作指南相关状态
const instructionsDialogVisible = ref(false)
const activeInstructionTab = ref('basic')

const currentImportType = ref<'transaction' | 'order'>('transaction')

// 计算属性
const pendingTransactions = computed(() => 
  reconciliationStore.pendingTransactions
  // 不再过滤 isFiltered 为 true 的记录
  // 过滤逻辑应该基于是否已被匹配，而不是 isFiltered 字段
  // .filter(t => !t.isFiltered)
)

const pendingOrders = computed(() => 
  reconciliationStore.pendingOrders
  // 暂时注释掉过滤逻辑来验证问题
  /* .filter(o => 
    !reconciliationStore.confirmedMatches.some(m => m.salesOrder.id === o.id)
  ) */
)

const workbenchStats = computed(() => ({
  pendingTransactions: pendingTransactions.value.length,
  pendingOrders: pendingOrders.value.length,
  matchedCount: reconciliationStore.confirmedMatches.length,
  accuracyRate: reconciliationStore.workbenchStats.accuracyRate,
  efficiencyScore: reconciliationStore.workbenchStats.efficiencyScore
}))

const selectedCounts = computed(() => ({
  transactions: selectedTransactions.value.length,
  orders: selectedOrders.value.length
}))

const matchStats = computed(() => ({
  total: matchResults.value.length,
  highConfidence: matchResults.value.filter((m: any) => m.confidence >= 80).length,
  mediumConfidence: matchResults.value.filter((m: any) => m.confidence >= 50 && m.confidence < 80).length,
  lowConfidence: matchResults.value.filter((m: any) => m.confidence < 50).length
}))

const canQuickMatch = computed(() => 
  selectedTransactions.value.length > 0 && selectedOrders.value.length > 0
)

// 方法
const loadWorkbenchData = async () => {
  transactionLoading.value = true
  orderLoading.value = true

  try {
    await Promise.all([
      reconciliationStore.loadPendingTransactions(),
      reconciliationStore.loadPendingOrders()
    ])
    
    // 检查是否需要显示智能助手
    if (pendingTransactions.value.length > 10 || pendingOrders.value.length > 10) {
      showSmartAssistant.value = true
    }
  } catch (error) {
    ElMessage.error('加载工作台数据失败')
  } finally {
    transactionLoading.value = false
    orderLoading.value = false
  }
}

const onTransactionSelect = (transactions: any[]) => {
  selectedTransactions.value = transactions
  checkSmartSuggestions()
}

const onOrderSelect = (orders: any[]) => {
  selectedOrders.value = orders
  checkSmartSuggestions()
}

const onTransactionFilter = (filters: any) => {
  // 处理银行流水过滤逻辑
  console.log('银行流水过滤:', filters)
}

const handleTransactionImport = () => {
  handleImportData('transaction')
}

const onTransactionClick = (transaction: any) => {
  // 高亮显示相关的订单
  const relatedOrders = findRelatedOrders(transaction)
  orderPanelRef.value?.highlightOrders(relatedOrders)
}

const onOrderClick = (order: any) => {
  // 高亮显示相关的流水
  const relatedTransactions = findRelatedTransactions(order)
  transactionPanelRef.value?.highlightTransactions(relatedTransactions)
}

const findRelatedOrders = (transaction: any) => {
  // 基于金额、时间等查找相关订单
  return pendingOrders.value.filter((order: any) => 
    Math.abs(order.amount - transaction.amount) < 0.01 ||
    order.customerName.includes(transaction.payerName) ||
    transaction.payerName.includes(order.customerName)
  )
}

const findRelatedTransactions = (order: any) => {
  // 基于金额、时间等查找相关流水
  return pendingTransactions.value.filter((transaction: any) => 
    Math.abs(transaction.amount - order.amount) < 0.01 ||
    transaction.payerName.includes(order.customerName) ||
    order.customerName.includes(transaction.payerName)
  )
}

const checkSmartSuggestions = () => {
  if (selectedTransactions.value.length === 1 && selectedOrders.value.length === 1) {
    const transaction = selectedTransactions.value[0]
    const order = selectedOrders.value[0]
    
    const confidence = calculateQuickConfidence(transaction, order)
    if (confidence >= 70) {
      matchSuggestions.value = [{
        type: 'quick_match',
        confidence,
        description: `建议匹配：${order.customerName} 的订单`,
        action: () => handleQuickMatch([transaction], [order])
      }]
    }
  }
}

const calculateNameSimilarity = (name1: string, name2: string) => {
  // 简单的名称相似度计算
  if (name1 === name2) return 100;
  if (name1.includes(name2) || name2.includes(name1)) return 80;
  return 0;
}

const calculateQuickConfidence = (transaction: any, order: any) => {
  let score = 0
  
  // 金额匹配 (权重 0.6)
  if (Math.abs(transaction.amount - order.amount) < 0.01) {
    score += 60
  }
  
  // 名称相似度 (权重 0.3)
  const nameSimilarity = calculateNameSimilarity(transaction.payerName, order.customerName)
  score += nameSimilarity * 30
  
  // 时间接近度 (权重 0.1)
  const timeDiff = Math.abs(new Date(transaction.transactionDate).getTime() - new Date(order.orderDate).getTime())
  const daysDiff = timeDiff / (1000 * 3600 * 24)
  if (daysDiff <= 7) score += 10
  else if (daysDiff <= 30) score += 5
  
  return Math.min(100, score)
}

const handleQuickMatch = async (transactions: any[], orders: any[]) => {
  processing.value = true
  try {
    const result = await reconciliationStore.manualMatch(
      transactions.map(t => t.id),
      orders.map(o => o.id),
      currentAlgorithm.value
    )
    ElMessage.success('匹配成功')
  } catch (error) {
    ElMessage.error('匹配失败')
  } finally {
    processing.value = false
  }
}

const handleSmartMatch = async (algorithm = 'comprehensive') => {
  currentAlgorithm.value = algorithm
  matchProgressVisible.value = true
  matchingStatus.value = 'matching'
  
  try {
    const results = await reconciliationStore.smartMatch(algorithm, (progress: any) => {
      matchProgress.value = progress
    })
    
    matchResults.value = results
    matchingStatus.value = 'success'
    
    ElMessage.success(`智能匹配完成，找到 ${results.length} 个匹配结果`)
    
    // 自动确认高置信度匹配
    const highConfidenceMatches = results.filter((m: any) => m.confidence >= 90)
    if (highConfidenceMatches.length > 0) {
      await handleBatchConfirm(highConfidenceMatches)
    }
  } catch (error) {
    matchingStatus.value = 'error'
    ElMessage.error('智能匹配失败')
  } finally {
    setTimeout(() => {
      matchProgressVisible.value = false
      matchingStatus.value = 'idle'
      matchProgress.value = 0
    }, 2000)
  }
}

const handleAlgorithmChange = (algorithm: string) => {
  currentAlgorithm.value = algorithm
  reconciliationStore.setCurrentAlgorithm(algorithm)
  // 可以在这里添加算法切换的逻辑
}

const onOrderFilter = (filters: any) => {
  // 处理订单过滤逻辑
  console.log('订单过滤:', filters)
}

const handleTransactionRefresh = async () => {
  transactionLoading.value = true
  try {
    await reconciliationStore.loadPendingTransactions()
    ElMessage.success('银行流水刷新成功')
  } catch (error) {
    ElMessage.error('银行流水刷新失败')
  } finally {
    transactionLoading.value = false
  }
}

const handleOrderSync = async () => {
  orderLoading.value = true
  try {
    await reconciliationStore.loadPendingOrders()
    ElMessage.success('订单同步成功')
  } catch (error) {
    ElMessage.error('订单同步失败')
  } finally {
    orderLoading.value = false
  }
}

const cancelSmartMatch = () => {
  // 取消智能匹配逻辑
  matchProgressVisible.value = false
  ElMessage.info('已取消智能匹配')
}

const handleConfirmMatch = async (matchId: string) => {
  processing.value = true
  try {
    await reconciliationStore.confirmMatch(matchId)
    ElMessage.success('确认匹配成功')
  } catch (error) {
    ElMessage.error('确认匹配失败')
  } finally {
    processing.value = false
  }
}

const handleRejectMatch = (matchId: string) => {
  // 拒绝匹配逻辑
  console.log('拒绝匹配:', matchId)
}

const handleBatchConfirm = async (matches: any[]) => {
  try {
    await reconciliationStore.batchConfirmMatches(matches.map(m => m.id))
    matches.forEach(match => { match.matchStatus = 'confirmed' })
    ElMessage.success(`批量确认 ${matches.length} 个匹配成功`)
  } catch (error) {
    ElMessage.error('批量确认失败')
  }
}

const showMatchDetails = async (match: any = null) => {
  currentMatch.value = match
  // 只有当match不为null时才尝试获取置信度分解
  if (match) {
    try {
      const breakdown = await reconciliationStore.getConfidenceBreakdown(match.id)
      confidenceBreakdown.value = breakdown
    } catch (error) {
      confidenceBreakdown.value = null
    }
  } else {
    confidenceBreakdown.value = null
  }
  detailsDrawerVisible.value = true
}

const handleImportData = (type: 'transaction' | 'order') => {
  currentImportType.value = type
  importWizardVisible.value = true
}

const handleImportSuccess = () => {
  loadWorkbenchData()
  ElMessage.success('数据导入成功')
}

const handleBatchOperate = () => {
  batchPanelVisible.value = true
}

const handleBatchMatch = () => {
  if (selectedTransactions.value.length > 0 && selectedOrders.value.length > 0) {
    handleQuickMatch(selectedTransactions.value, selectedOrders.value)
  }
}

const handleBatchIgnore = () => {
  // 批量忽略选中的流水
  reconciliationStore.batchIgnoreTransactions(selectedTransactions.value.map((t: any) => t.id))
  selectedTransactions.value = []
  ElMessage.success('已忽略选中的流水')
}

const applySmartSuggestion = (suggestion: any) => {
  suggestion.action()
}

const clearAllSelection = () => {
  selectedTransactions.value = []
  selectedOrders.value = []
  // 清除子组件中的选中状态
  transactionPanelRef.value?.onSelectionChange([])
  orderPanelRef.value?.onSelectionChange([])
}

// 显示操作指南
const showInstructions = () => {
  instructionsDialogVisible.value = true
}

// 面板拖拽调整
const startResize = (direction: 'left' | 'right') => {
  isResizing.value = true
  resizeDirection.value = direction
  
  const handleMouseMove = (e: MouseEvent) => {
    if (!isResizing.value) return
    
    if (resizeDirection.value === 'left') {
      leftPanelWidth.value = Math.max(300, Math.min(600, e.clientX))
    } else {
      const rightPosition = window.innerWidth - e.clientX
      rightPanelWidth.value = Math.max(300, Math.min(600, rightPosition))
    }
  }
  
  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 生命周期
onMounted(() => {
  loadWorkbenchData()
  
  // 监听键盘快捷键
  document.addEventListener('keydown', handleKeydown)
})

// 键盘快捷键
const handleKeydown = (e: KeyboardEvent) => {
  if (e.target instanceof HTMLInputElement) return
  
  // Ctrl/Cmd + M: 智能匹配
  if ((e.ctrlKey || e.metaKey) && e.key === 'm') {
    e.preventDefault()
    handleSmartMatch(currentAlgorithm.value)
  }
  
  // Ctrl/Cmd + Q: 快速匹配选中项
  if ((e.ctrlKey || e.metaKey) && e.key === 'q' && canQuickMatch.value) {
    e.preventDefault()
    handleQuickMatch(selectedTransactions.value, selectedOrders.value)
  }
  
  // Escape: 清除选择
  if (e.key === 'Escape') {
    clearAllSelection()
  }
}
</script>

<style scoped lang="scss">
.smart-reconciliation-workbench {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  
  .workbench-main {
    flex: 1;
    display: flex;
    position: relative;
    overflow: hidden;
    
    .panel-left,
    .panel-right {
      position: relative;
      background: white;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      transition: width 0.3s ease;
      z-index: 1;
      
      .panel-resize-handle {
        position: absolute;
        top: 0;
        right: 0;
        width: 4px;
        height: 100%;
        background: transparent;
        cursor: col-resize;
        z-index: 10;
        
        &:hover {
          background: rgba(24, 144, 255, 0.3);
        }
        
        &::after {
          content: '';
          position: absolute;
          top: 50%;
          right: 1px;
          transform: translateY(-50%);
          width: 2px;
          height: 40px;
          background: #1890ff;
          border-radius: 1px;
          opacity: 0;
          transition: opacity 0.3s ease;
        }
        
        &:hover::after {
          opacity: 1;
        }
      }
    }
    
    .panel-left {
      border-right: 1px solid #f0f0f0;
    }
    
    .panel-right {
      border-left: 1px solid #f0f0f0;
      
      .panel-resize-handle {
        left: 0;
        right: auto;
        
        &::after {
          left: 1px;
          right: auto;
        }
      }
    }
    
    .panel-center {
      flex: 1;
      display: flex;
      flex-direction: column;
      position: relative;
      min-width: 400px;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .workbench-main {
    flex-direction: column !important;
    
    .panel-left,
    .panel-right,
    .panel-center {
      width: 100% !important;
      height: 33.333%;
    }
    
    .panel-resize-handle {
      display: none;
    }
  }
}

// 拖拽调整时的样式
:global(.resizing) {
  user-select: none;
  cursor: col-resize;
}
</style>